﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SoundManager : MonoBehaviour {
    private static SoundManager _instance;//单例模式
    public static SoundManager _Instance { get { return _instance; } }
    private AudioSource audioSource_BG;
    private float Volume_BG ;
    public string ResourcesDir = "Sounds";
    private bool isPlay;
    private bool isR = true;
    private void Awake()
    {
        _instance = this;
        DontDestroyOnLoad(gameObject);
        audioSource_BG = GetComponent<AudioSource>();
        audioSource_BG.loop = true;
        audioSource_BG.playOnAwake = false;        
    }
    private void Update()
    {
        audioSource_BG.volume = Volume;
        if (isPlay&&isR)
        {
            isR = false;//播放后就不再进入该判断
            ResumePlayMusic();
        }
        else if(!isPlay&&!isR)
        {
            isR = true;//停止后就不再进入该判断
            StopPlayMusic();
        }
            
    }
    public float Volume { get { return Volume_BG; }set { Volume_BG = value; } }
    public bool IsPlay { get { return isPlay; }set { isPlay = value; } }
    //播放背景音乐（循环）
    public void PlayBGMusicByName(string name)
    {
        string path = ResourcesDir + "/" + name;
        AudioClip clip = Resources.Load<AudioClip>(path);
        if (clip != null)
        {
            audioSource_BG.clip = clip;
            //audioSource_BG.Play();
        }
    }
    //停止播放
    public void StopPlayMusic()
    {
        audioSource_BG.Stop();
       // audioSource_BG.clip = null;
    }
    //开始播放
    public void ResumePlayMusic()
    {
        audioSource_BG.Play();
    }
    //播放音效（短暂）
    public void PlaySoundByName(string name)
    {
        string path = ResourcesDir + "/" + name;
        AudioClip clip = Resources.Load<AudioClip>(path);
        if (clip != null)
        {
            AudioSource.PlayClipAtPoint(clip, Camera.main.transform.position);
        }
    }
}
